package com.gistmap.ntdc.interceptor;

import com.alibaba.fastjson.JSON;
import com.gistmap.ntdc.exception.ErrorItems;
import com.gistmap.ntdc.persistence.domain.User;
import com.gistmap.ntdc.response.Result;
import com.gistmap.ntdc.service.UserService;
import com.gistmap.ntdc.util.SessionUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * @author zhangran
 * @date 2018/12/20
 */
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        if (StringUtils.isBlank(token)) {
            makeFail(response);
            return false;
        }
        log.info("token : {}" ,token);
        User user = userService.findByToken(token);
        if (user == null) {
            makeFail(response);
            return false;
        }
        SessionUtil.setUser(user);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        // 请求结束
        // 请求结束以后移除 user
        SessionUtil.removeUser();
    }

    public void makeFail(HttpServletResponse response){
        Result result = new Result().error(ErrorItems.NO_USER);
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        try {
            PrintWriter out = response.getWriter();
            out.print(JSON.toJSONString(result));
            out.close();
        } catch (Exception e) {
            log.error("LoginInterceptor preHandle ", e);
        }
    }
}
